package com.lipl.base.javaee.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Auther: 15541
 * @Date: 2020/11/6 15:35
 * @Description:
 */
public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static  final int PORT = 6667;

    //构造器
    public GroupChatServer(){
        try {
            //得到选择器
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){

        try{
            //循环处理
            while(true){
                int count = selector.select(2000);
                if(count > 0){//有时间处理

                    //遍历得到selectionkey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();

                        //监听到accept
                        if(key.isAcceptable()){
                            SocketChannel sc = listenChannel.accept();
                            //讲改sc注册到selector
                            sc.register(selector,SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress()+"上线");
                        }

                        if (key.isReadable()){//通道发送read事件，即通道是可读的状态

                        }

                        //当前的key 删除，防止重复处理
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待.....");
                }
            }
        }catch (Exception e){
            e.printStackTrace();

        }finally {

        }
    }

    //读取客户端消息
    private void readData(SelectionKey key){

        SocketChannel channel = null;
        try {
            //得到channel
            channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            int count = channel.read(byteBuffer);
            //根据count的值做处理
            if(count > 0){
                String msg = new String(byteBuffer.array());
                //输出
                System.out.println("from 客户端:" + msg);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

    }
}

